// pages/reviewRecord/takesTwo/takesTwo.js
const app = getApp();
let tool = require('../../../utils/tool.js');
const httpUtils = require('../../../utils/httpUtils.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    innerAudioContext: new Object(),
    gameSecond: 50, //过关时间
    gameSecond2: 0,
    maskDis: 'flex',
    jbDis: 'flex',
    ggDis: 'none',
    gfDis: 'none',
    passNum: '0',
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    wrongWorlds: [],
    curworng: -1,
    worldsEn: '',
    worldsCh: '',
    rightNum: 6,
    curentChoice: {
      'en': -1,
      'ch': -1
    },
    rightArr: new Array(),
    timer: '',
	timerdata:[],
    allword: [],
    errword: [],
    curentIdx: false,
    clickArr: [],
    reviewTime: 0,
    replayFlag: false,
    date: '', //学习日期
    sort: '2', //作业形式 1 词义闯关 2 对对碰 3 廷议释义 4 组合拼 5读一遍 6 写一遍
    task_id: '', //任务id
    wordLen: 6, //本关共多少词
    errNum: 0, //本关错词数
    isNextPassFlag: false,
    can_submit: 1, //1 可以提交 0不可以提交
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //获取传过来的日期
    that.setData({
      task_id: options.task_id,
      date: options.date,
      can_submit: options.can_submit
    })
    console.log(that.data.date)
    this.data.innerAudioContext = wx.createInnerAudioContext()
    this.data.innerAudioContext.autoplay = false;
    this.data.innerAudioContext.loop = false;
    this.data.innerAudioContext.src = app.globalData.mp3.selected;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // clearInterval(this.data.timer);
	this.cleartime();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },

  playmp3: function (mp3url) { //播放音效
    this.data.innerAudioContext.src = mp3url;
    this.data.innerAudioContext.play();

  },

  setSec: function (e) { //设置描述
    let that = this;
    if (!this.data.replayFlag) {
      console.log("选时间，下一关")
      this.setData({
        maskDis: 'none',
        jbDis: 'none',
        gfDis: 'none',
        gameSecond2: e.currentTarget.dataset.passsce,
        gameSecond: e.currentTarget.dataset.passsce
      });

      // clearInterval(this.data.timer);
	  that.cleartime();
      that.initDdata();
      that.getData();
      if (this.data.gameSecond2 > 0) {
        this.daojishi();
      }
      // this.nextPass();
    } else {
      console.log("选时间，重玩本关")
      this.setData({
        maskDis: 'none',
        jbDis: 'none',
        gameSecond2: e.currentTarget.dataset.passsce,
        gameSecond: e.currentTarget.dataset.passsce,
        wrongWorlds: [],
        curworng: -1,
        rightNum: 6,
        curentChoice: {
          'en': -1,
          'ch': -1
        },
        rightArr: new Array(),
        timer: '',
        allword: [],
        errword: [],
        curentIdx: false,
        clickArr: [],
        reviewTime: 0,
        replayFlag: false,
        allNum: 0,
        errNum: 0,
        isNextPassFlag: false
      })
      //重玩
      this.rePass();
    }

  },
  choiceOption: function (e) { //选择选项
    let that = this;
    this.setData({
      curworng: -1
    });
    let btype = e.currentTarget.dataset.type;
    let key = e.currentTarget.dataset.yindex;

    if (btype == 'en') {
      this.playmp3(app.globalData.mp3.selected);
      this.data.curentIdx = e.currentTarget.dataset.idx;
      this.setData({
        curentChoice: {
          'en': key,
          'ch': "-1"
        }
      })
    }
    if (btype == 'ch') {
      if (this.data.curentChoice.en == '-1') { //没有选中英文无任何操作
        return;
      }
      if (this.data.curentChoice.en == key) { //选对了
        //记录被点击过的英文
        if (this.data.clickArr.indexOf(this.data.curentIdx) == -1) {
          this.data.clickArr.push(this.data.curentIdx);
        }
        this.playmp3(app.globalData.mp3.doright);
        let temparr = this.data.rightArr;
        if (temparr.indexOf(key) == -1) {
          temparr.push(key)
        }
        this.setData({
          rightArr: temparr,
          curentChoice: this.data.curentChoice,
          curentChoice: {
            'en': "-1",
            'ch': "-1"
          }
        });

        console.log("rightArr.length=" + this.data.rightArr.length);
        if(that.data.rightArr.length ==6){
          // clearInterval(that.data.timer);
		  that.cleartime();
          that.judgeAndPop();
        }else if (this.data.worldsEn.length <= 6 && this.data.rightArr.length == this.data.worldsEn.length - 1) {
          console.log("---------最后小于6个英文单词情况，剩余" + (that.data.worldsEn.length - 1))
          console.log("最后一个选项了")
          that.judgeAndPop();
          // clearInterval(that.data.timer);
		  that.cleartime();
        }

      
      } else {
        //选错了
        app.vibrateShortTap();
        let temparr = this.data.wrongWorlds;
        this.playmp3(app.globalData.mp3.selectwrong)
        if (temparr.indexOf(key) == -1) {
          temparr.push(key);
        }
        if (that.data.errword.indexOf(that.data.worldsEn[that.data.curentIdx]['word']) == -1) {
          that.data.errword.push(that.data.worldsEn[that.data.curentIdx]['word']);
        }

        that.setData({
          wrongWorlds: temparr,
          curworng: key
        })
      }
    }
  },
  cleartime(){
	  for (var i = 0; i < this.data.timerdata.length; i++) {
	  		clearInterval(this.data.timerdata[i]);
	  }
  },
  daojishi: function () { //倒计时
    let that = this;
    that.data.timer = setInterval(function () {
      app.globalData.taskTwoMinuts = app.globalData.taskTwoMinuts + 1;
      let num = parseInt(that.data.gameSecond) - 1
      if (num < 10 && num >= 0) {
        num = "0" + num.toString();
      }
      that.setData({
        gameSecond: num
      });

      if (parseInt(that.data.gameSecond) <= 0) {
        // clearInterval(that.data.timer);
		that.cleartime();
        console.log("倒计时结束，")
        that.judgeAndPop();
    
      }
    }, 1000);
	that.data.timerdata.push(that.data.timer)
  },

  //判断是否通关，并弹对应的弹窗
  judgeAndPop() {
    let that = this;
    that.collectWrong();
    let num = parseInt((that.data.worldsEn.length - 1) / 2);
    let errNum = that.data.errword.length>6? 6 :that.data.errword.length-1;

    console.log("计算错词并比较，标准num=" + num + "，errnum=" + errNum + ",错词为：" + that.data.errword)
  
    if (errNum <= num) {
      that.setData({
        errNum: errNum,
        allNum:that.data.allword.length-1,
        ggDis: 'flex',
        gfDis:'none',
        maskDis: 'flex'
      });
    } else {
      that.setData({
        errNum: errNum,
        allNum:that.data.allword.length-1,
        gfDis: 'flex',
        ggDis:'none',
        maskDis: 'flex',
        replayFlag: true
      });
    }
  },


  nextPass: function () { //进入下一关
    let that = this;
    // if (that.data.passNum > 0) {
    //   that.collectWrong();
    // }
    console.log("错词" + that.data.errNum + "个，点击了下一关")
    this.setData({
      gameSecond: this.data.gameSecond2,
      maskDis: 'none',
      ggDis: 'none',
      gfDis: 'none',
      isNextPassFlag: true
    });
    // clearInterval(this.data.timer);
	that.cleartime();
    that.submitAnswer();
 

    // that.initDdata();
    // that.getData();
    // if (this.data.gameSecond2 > 0) {
    //   this.daojishi();
    // }
  },

  //获取数据
  getData: function () {
    var that = this;
    wx.showLoading({
      title: '',
      mask: true
    })

    httpUtils.getWordPopReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      page: parseInt(that.data.passNum) + 1,
    }).then((res) => {
      wx.hideLoading();
      let list = res.data;

      // if (list.length < 1 || list[0].length < 2) {
      //   console.log("获取数据，已无数据跳转报告页")
      //   wx.redirectTo({
      //     url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
      //   })
      //   return;
      // };

      that.data.passNum = parseInt(that.data.passNum) + 1; //过关数
      that.setData({
        worldsEn: list[0],
        worldsCh: list[1],
        passNum: that.data.passNum
      })

    });
  },

  initDdata: function () { //过关初始化数据
    this.setData({
      wrongWorlds: [],
      curworng: -1,
      worldsEn: '',
      worldsCh: '',
      rightNum: 6,
      curentChoice: {
        'en': -1,
        'ch': -1
      },
      rightArr: new Array(),
      clickArr: new Array(),
      allword: [],
      errword: [],
    })
  },

  //点击弹窗中的不想玩了按钮
  toReport: function () { //跳转到报告页面
    let that = this;
    // that.collectWrong();
    that.setData({
      isNextPassFlag: false
    })
    that.submitAnswer();
 
  },

  //提交结果
  submitAnswer: function () {
    let that = this;
    that.collectWrong();
    console.log("调提交答案接口,错词" + this.data.errword.length+",errorword为："+JSON.stringify(that.data.errword))
    console.log("allword=" + that.data.allword.length)
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    httpUtils.submitWordReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sort: that.data.sort,
      pic: "",
      stu_answer: "",
      allword: that.data.allword.join(','),
      errword: that.data.errword.join(','),
    }).then((res) => {
      wx.hideLoading();
      let remainword = res.data.remain;
      if (remainword <= 0) {
        console.log("剩余单词数小于等于0了，提交完成直接跳报告页")
        setTimeout(function () {
          wx.showToast({
            title: "恭喜你完成复习~",
            icon: 'none',
            duration: 2000
          });
        }, 500)
        wx.redirectTo({
          url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
        })
        return;
      }

      console.log("提交成功~isNextPassFlag=" + that.data.isNextPassFlag)
      if (that.data.isNextPassFlag) {
        console.log("初始化数据，并获取下一关的数据")
        that.initDdata();
        that.getData();
        if (this.data.gameSecond2 > 0) {
          this.daojishi();
        }
      }else{
        console.log("点不想玩了，提交成功，跳转报告页")
        wx.redirectTo({
          url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
        })
      }
    });

  },

  //清算本关错误单词
  collectWrong: function () {
    let that = this;
    for (let idx in that.data.worldsEn) {
      if (that.data.clickArr.indexOf(parseInt(idx)) == -1) {
        if (that.data.errword.indexOf(that.data.worldsEn[idx].word) == -1) {
          that.data.errword.push(that.data.worldsEn[idx].word);
        }
      }
      if (this.data.allword.indexOf(this.data.worldsEn[idx].word) == -1) {
        this.data.allword.push(this.data.worldsEn[idx].word);
      }
    }
    let errNum = that.data.errword.length>6? 6 :that.data.errword.length-1;
    that.setData({
      errNum:errNum
    })
    console.log("清算本关错误单词,errword=" + JSON.stringify(that.data.errword))

  },

  //点击弹窗中重玩本关的按钮
  replay: function () {
    this.setData({
      jbDis: 'flex',
      gfDis: 'none'
    })
  },

  //重玩
  rePass: function () {
    // clearInterval(this.data.timer);
	this.cleartime();
    if (this.data.gameSecond2 > 0) {
      this.daojishi();
    }
  }
})